//
//  HMCycleView.m
//  轮播
//
//  Created by HaoYoson on 16/7/3.
//  Copyright © 2016年 HaoYoson. All rights reserved.
//

#import "HMCycleCell.h"
#import "HMCycleFlowLayout.h"
#import "HMCycleView.h"
#import "Masonry.h"
#import "UIColor+Addition.h"

#define kSeed 998

static NSString *cellid = @"cycle_cell";

@interface HMCycleView () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (weak, nonatomic) UICollectionView *collectionView;
@property (weak, nonatomic) UIPageControl *pageControl;

@property (strong, nonatomic) NSTimer *timer;

@end

@implementation HMCycleView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (void)awakeFromNib {
    [self setupUI];
}

- (void)setupUI {
    // 子控件
    HMCycleFlowLayout *layout = [[HMCycleFlowLayout alloc] init];
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.pagingEnabled = YES;
    collectionView.bounces = NO;
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.showsHorizontalScrollIndicator = NO;
    [collectionView registerClass:[HMCycleCell class] forCellWithReuseIdentifier:cellid];    // 注册
    [self addSubview:collectionView];

    UIPageControl *pageControl = [[UIPageControl alloc] init];
    pageControl.currentPageIndicatorTintColor = [UIColor blueColor];
    pageControl.pageIndicatorTintColor = [UIColor blackColor];
    [self addSubview:pageControl];

    // 自动布局
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];

    [pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.bottom.offset(-4);
    }];

    self.collectionView = collectionView;
    self.pageControl = pageControl;
}

- (void)setImageURLs:(NSArray *)imageURLs {
    _imageURLs = imageURLs;

    [self.collectionView reloadData];

    [self.collectionView layoutIfNeeded];

    // 滚动的起始位置
    //    self.collectionView.contentOffset = CGPointMake(imageURLs.count * kSeed * self.collectionView.bounds.size.width, 0);

    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:imageURLs.count * kSeed inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];

    self.pageControl.numberOfPages = imageURLs.count;
    self.pageControl.currentPage = 0;

    //
    //    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];

    NSTimer *timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

    self.timer = timer;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.timer.fireDate = [NSDate distantFuture];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    self.timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:2];
}

- (void)updateTimer {
    NSIndexPath *path = [self.collectionView indexPathsForVisibleItems].lastObject;
    NSIndexPath *newPath = [NSIndexPath indexPathForItem:path.item + 1 inSection:path.section];

    [self.collectionView scrollToItemAtIndexPath:newPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];

    // 手动调用已经停止的方法
    [self scrollViewDidEndDecelerating:self.collectionView];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGFloat offsetX = scrollView.contentOffset.x;
    NSInteger page = offsetX / self.collectionView.bounds.size.width;

    NSLog(@"%zd", page);

    // 第0页的时候 到3
    // 第5页(imageURLs.count * 2- 1)的时候 到2

    if (page == 0) {    // 第一页
        scrollView.contentOffset = CGPointMake(offsetX += _imageURLs.count * kSeed * self.collectionView.bounds.size.width, 0);
    } else if (page == [self.collectionView numberOfItemsInSection:0] - 1) {    // 最后一页
        scrollView.contentOffset = CGPointMake(offsetX -= _imageURLs.count * kSeed * self.collectionView.bounds.size.width, 0);
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offsetX = scrollView.contentOffset.x;
    CGFloat page = (offsetX / self.collectionView.bounds.size.width) + 0.5;
    self.pageControl.currentPage = (NSInteger)page % self.imageURLs.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.imageURLs.count * 2 * kSeed;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HMCycleCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellid forIndexPath:indexPath];

    cell.imageURL = self.imageURLs[indexPath.item % self.imageURLs.count];

    return cell;
}

- (void)removeFromSuperview {
    [super removeFromSuperview];
    [self.timer invalidate];
}

@end
